package org.seven.jrdp.commons.shiro.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.seven.jrdp.commons.shiro.service.ResourceService;
import org.seven.jrdp.commons.util.ServletUtils;

public class PermissionFilter extends AuthorizationFilter {
	private ResourceService resourceService;

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	@Override
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		Subject subject = getSubject(request, response);
		String url = getPathWithinApplication(request);
		Map<String, String> map = resourceService.getResourceMap();
		String permissions = map.get(url);
		if (permissions != null) {
			boolean[] isPermitteds = subject.isPermitted(permissions.split(","));
			for (boolean isPermitted : isPermitteds) {
				if (isPermitted) {
					return true;
				}
			}
			if (ServletUtils.isAjax(WebUtils.toHttp(request))) {
				WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
			} else {
				WebUtils.issueRedirect(request, response, getUnauthorizedUrl());
			}
			return false;
		}
		return true;
	}
}